package leetcode; /**
 * description:
 * author:张腾
 * date:2021-07-07
 */

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 给定一个可包含重复数字的序列 nums ，按任意顺序 返回所有不重复的全排列。
 */
public class leetcode47 {
    public static void main(String[] args) {
        System.out.println(new leetcode47().permuteUnique(new int[]{3,3,0,3}));
    }
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    boolean[] visited;
    public List<List<Integer>> permuteUnique(int[] nums) {
        int n = nums.length;
        if (n==0 || nums==null) return res;
        //重点！！！
        Arrays.sort(nums);

        visited = new boolean[n];
        dfs(nums,0,n);

        return res;
    }

    public void dfs(int[] nums,int depth,int len){
        if (depth==len){
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < len; i++) {
            if (i>0 && nums[i]==nums[i-1] && !visited[i-1]) continue;
            if (!visited[i]){
                visited[i] = true;
                path.add(nums[i]);
                dfs(nums,depth+1,len);
                visited[i] = false;
                path.remove(path.size()-1);
            }
        }
    }
}
